<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Reward extends Common
{
    /**
     * 社区服务站
     * */
    public function setCommunityRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $community_vip_count = $input['community_vip_count'];
            $community_vip_consume = $input['community_vip_consume'];
            $community_own_consume = $input['community_own_consume'];

            if (empty($community_vip_count)) adminReturn(2, '请输入VIP数量');
            if (empty($community_vip_consume)) adminReturn(2, '请输入消费金额');
            if (empty($community_own_consume)) adminReturn(2, '请输入自行消费金额');

            Db::startTrans();
            try {
                Db::name('user_up_rule')->where(['name' => 'community_vip_count'])->setField('value', $community_vip_count);
                Db::name('user_up_rule')->where(['name' => 'community_vip_consume'])->setField('value', $community_vip_consume);
                Db::name('user_up_rule')->where(['name' => 'community_own_consume'])->setField('value', $community_own_consume);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $community_vip_count_value = Db::name('user_up_rule')->where(['name' => 'community_vip_count'])->value('value');
            $community_vip_consume_value = Db::name('user_up_rule')->where(['name' => 'community_vip_consume'])->value('value');
            $community_own_consume_value = Db::name('user_up_rule')->where(['name' => 'community_own_consume'])->value('value');

            $this->assign('community_vip_count_value', $community_vip_count_value);
            $this->assign('community_vip_consume_value', $community_vip_consume_value);
            $this->assign('community_own_consume_value', $community_own_consume_value);

            $this->assign('title', '社区服务站');
            return $this->view->fetch();
        }
    }

    /**
     * 县区服务站
     * */
    public function setCountyRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $county_diff_community_count = $input['county_diff_community_count'];
            $county_all_consume = $input['county_all_consume'];

            if (empty($county_diff_community_count)) adminReturn(2, '请输入不同线社区服务站数量');
            if (empty($county_all_consume)) adminReturn(2, '请输入总累计业绩');

            Db::startTrans();
            try {
                Db::name('user_up_rule')->where(['name' => 'county_diff_community_count'])->setField('value', $county_diff_community_count);
                Db::name('user_up_rule')->where(['name' => 'county_all_consume'])->setField('value', $county_all_consume);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $county_diff_community_count = Db::name('user_up_rule')->where(['name' => 'county_diff_community_count'])->value('value');
            $county_all_consume = Db::name('user_up_rule')->where(['name' => 'county_all_consume'])->value('value');

            $this->assign('county_diff_community_count', $county_diff_community_count);
            $this->assign('county_all_consume', $county_all_consume);

            $this->assign('title', '县区服务站');
            return $this->view->fetch();
        }
    }

    /**
     * 城市服务站
     * */
    public function setCityRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $city_diff_county_count = $input['city_diff_county_count'];
            $city_all_consume = $input['city_all_consume'];

            if (empty($city_diff_county_count)) adminReturn(2, '请输入不同线县区服务站数量');
            if (empty($city_all_consume)) adminReturn(2, '请输入总累计业绩');

            Db::startTrans();
            try {
                Db::name('user_up_rule')->where(['name' => 'city_diff_county_count'])->setField('value', $city_diff_county_count);
                Db::name('user_up_rule')->where(['name' => 'city_all_consume'])->setField('value', $city_all_consume);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $city_diff_county_count = Db::name('user_up_rule')->where(['name' => 'city_diff_county_count'])->value('value');
            $city_all_consume = Db::name('user_up_rule')->where(['name' => 'city_all_consume'])->value('value');

            $this->assign('city_diff_county_count', $city_diff_county_count);
            $this->assign('city_all_consume', $city_all_consume);

            $this->assign('title', '城市服务站');
            return $this->view->fetch();
        }
    }

    /**
     * 设置ZJ销售系数
     * */
    public function setShareRate()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $vip = $input['vip'];
            $community = $input['community'];
            $county = $input['county'];
            $city = $input['city'];

            if (empty($vip)) adminReturn(2, '请输入vip直推比例');
            if (empty($community)) adminReturn(2, '请输入社区服务站直推比例');
            if (empty($county)) adminReturn(2, '请输入县区服务站直推比例');
            if (empty($city)) adminReturn(2, '请输入城市服务站直推比例');

            Db::startTrans();
            try {
                Db::name('share_rate')->where(['name' => 'vip'])->setField('value', $vip);
                Db::name('share_rate')->where(['name' => 'community'])->setField('value', $community);
                Db::name('share_rate')->where(['name' => 'county'])->setField('value', $county);
                Db::name('share_rate')->where(['name' => 'city'])->setField('value', $city);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $vip = Db::name('share_rate')->where(['name' => 'vip'])->value('value');
            $community = Db::name('share_rate')->where(['name' => 'community'])->value('value');
            $county = Db::name('share_rate')->where(['name' => 'county'])->value('value');
            $city = Db::name('share_rate')->where(['name' => 'city'])->value('value');

            $this->assign('vip', $vip);
            $this->assign('community', $community);
            $this->assign('county', $county);
            $this->assign('city', $city);

            $this->assign('title', '设置ZJ销售系数');
            return $this->view->fetch();
        }
    }

    /**
     * 设置服务津贴比例
     * */
    public function setAllowanceRate()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $community = $input['community'];
            $county = $input['county'];
            $city = $input['city'];

            if (empty($community)) adminReturn(2, '请输入社区服务站服务津贴比例');
            if (empty($county)) adminReturn(2, '请输入县区服务站服务津贴比例');
            if (empty($city)) adminReturn(2, '请输入城市服务站服务津贴比例');

            Db::startTrans();
            try {
                Db::name('allowance_rate')->where(['name' => 'community'])->setField('value', $community);
                Db::name('allowance_rate')->where(['name' => 'county'])->setField('value', $county);
                Db::name('allowance_rate')->where(['name' => 'city'])->setField('value', $city);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $community = Db::name('allowance_rate')->where(['name' => 'community'])->value('value');
            $county = Db::name('allowance_rate')->where(['name' => 'county'])->value('value');
            $city = Db::name('allowance_rate')->where(['name' => 'city'])->value('value');

            $this->assign('community', $community);
            $this->assign('county', $county);
            $this->assign('city', $city);

            $this->assign('title', '设置服务津贴比例');
            return $this->view->fetch();
        }
    }

    /**
     * 设置首单规则
     * */
    public function setFirstOrderRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $first_order_min_price = $input['first_order_min_price'];
            $less_min_price_msg = $input['less_min_price_msg'];

            if (empty($first_order_min_price)) adminReturn(2, '请输入首单最小金额');
            if (empty($less_min_price_msg)) adminReturn(2, '请输入金额不足提示语');

            Db::startTrans();
            try {
                Db::name('profit_rule')->where(['name' => 'first_order_min_price'])->setField('value', $first_order_min_price);
                Db::name('profit_rule')->where(['name' => 'less_min_price_msg'])->setField('value', $less_min_price_msg);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $first_order_min_price = Db::name('profit_rule')->where(['name' => 'first_order_min_price'])->value('value');
            $less_min_price_msg = Db::name('profit_rule')->where(['name' => 'less_min_price_msg'])->value('value');

            $this->assign('first_order_min_price', $first_order_min_price);
            $this->assign('less_min_price_msg', $less_min_price_msg);

            $this->assign('title', '设置首单规则');
            return $this->view->fetch();
        }
    }

    /**
     * 设置销售奖励比例
     * */
    public function setSalesBonusRate()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $bonus_rate = $input['bonus_rate'];

            Db::startTrans();
            try {
                Db::name('sales_bonus_rate')->where(['name' => 'bonus_rate'])->setField('value', $bonus_rate);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $bonus_rate = Db::name('sales_bonus_rate')->where(['name' => 'bonus_rate'])->value('value');

            $this->assign('bonus_rate', $bonus_rate);

            $this->assign('title', '设置销售奖励比例');
            return $this->view->fetch();
        }
    }

    /**
     * 设置退休基金规则
     * */
    public function setRetireFundRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $first_gear_rate = $input['first_gear_rate'];
            $second_gear_rate = $input['second_gear_rate'];
            $third_gear_rate = $input['third_gear_rate'];
            $first_gear_diff_city_circuit = $input['first_gear_diff_city_circuit'];
            $second_gear_diff_first_circuit = $input['second_gear_diff_first_circuit'];
            $third_gear_diff_second_circuit = $input['third_gear_diff_second_circuit'];

            Db::startTrans();
            try {
                Db::name('retire_fund_rule')->where(['name' => 'first_gear_rate'])->setField('value', $first_gear_rate);
                Db::name('retire_fund_rule')->where(['name' => 'second_gear_rate'])->setField('value', $second_gear_rate);
                Db::name('retire_fund_rule')->where(['name' => 'third_gear_rate'])->setField('value', $third_gear_rate);
                Db::name('retire_fund_rule')->where(['name' => 'first_gear_diff_city_circuit'])->setField('value', $first_gear_diff_city_circuit);
                Db::name('retire_fund_rule')->where(['name' => 'second_gear_diff_first_circuit'])->setField('value', $second_gear_diff_first_circuit);
                Db::name('retire_fund_rule')->where(['name' => 'third_gear_diff_second_circuit'])->setField('value', $third_gear_diff_second_circuit);

                Db::commit();
                adminReturn(1, '保存成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~');
            }
        } else {
            $first_gear_rate = Db::name('retire_fund_rule')->where(['name' => 'first_gear_rate'])->value('value');
            $second_gear_rate = Db::name('retire_fund_rule')->where(['name' => 'second_gear_rate'])->value('value');
            $third_gear_rate = Db::name('retire_fund_rule')->where(['name' => 'third_gear_rate'])->value('value');
            $first_gear_diff_city_circuit = Db::name('retire_fund_rule')->where(['name' => 'first_gear_diff_city_circuit'])->value('value');
            $second_gear_diff_first_circuit = Db::name('retire_fund_rule')->where(['name' => 'second_gear_diff_first_circuit'])->value('value');
            $third_gear_diff_second_circuit = Db::name('retire_fund_rule')->where(['name' => 'third_gear_diff_second_circuit'])->value('value');

            $this->assign('first_gear_rate', $first_gear_rate);
            $this->assign('second_gear_rate', $second_gear_rate);
            $this->assign('third_gear_rate', $third_gear_rate);
            $this->assign('first_gear_diff_city_circuit', $first_gear_diff_city_circuit);
            $this->assign('second_gear_diff_first_circuit', $second_gear_diff_first_circuit);
            $this->assign('third_gear_diff_second_circuit', $third_gear_diff_second_circuit);

            $this->assign('title', '退休基金规则');
            return $this->view->fetch();
        }
    }

    /**
     * 获取用户列表
     * */
    public function getUserList($user_id = 0)
    {
//        $user_list = Db::name('user')->field('id,username,up_user_id,level')->where(['id' => ['gt', 1], 'up_user_id' => $user_id])->order('id asc')->select();
        $user_list = Db::name('user')->where(['id' => ['gt', 1], 'up_user_id' => $user_id])->order('id asc')->select();
        if ($user_list) {
            foreach ($user_list as &$v) {
                $son_user_list = $this->getUserList($v['id']);
                $v['son_user_list'] = $son_user_list;
            }
        }

        return $user_list;
    }

    /**
     * 用户注册
     * */
    public function simulationUserRegister()
    {
        $user_list = $this->getUserList();
        $this->assign('user_list', $user_list);
        $this->assign('user_list_json', json_encode($user_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '用户注册');
        return $this->view->fetch();
    }

    /**
     * 生成随机手机号
     * */
    public function randMobile()
    {
        $arr = array(
            130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
            144, 147,
            150, 151, 152, 153, 155, 156, 157, 158, 159,
            176, 177, 178,
            180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
        );

        $mobile = $arr[array_rand($arr)] . mt_rand(1000, 9999) . mt_rand(1000, 9999);

        return $mobile;
    }

    /**
     * 删除一维数组中值为0的元素
     * */
    public function delArrZero($arr)
    {
        $key = array_search(0, $arr);
        if ($key > -1) {
            array_splice($arr, $key, 1);
            if (array_search(0, $arr)) {
                return $this->delArrZero($arr);
            } else {
                return $arr;
            }
        } else {
            return $arr;
        }
    }

    /**
     * 模拟注册用户
     * */
    public function registerUser()
    {
        $input = Request()->param();

        $username = $input['username'];
        $level = $input['level'];
        $up_user_id_arr = $input['up_user_id'];

        if (empty($username)) adminReturn(2, '请输入用户名');

        $up_user_id_arr = $this->delArrZero($up_user_id_arr);

        $up_user_id = $up_user_id_arr[count($up_user_id_arr) - 1] ? : 0;

        $data = [
            'username' => $username,
            'level' => $level,
            'up_user_id' => $up_user_id,
            'mobile' => $this->randMobile(),
            'openid' => uniqid()
        ];

        $res = Db::name('user')->insert($data);
        if ($res) {
            adminReturn(1, '注册成功');
        } else {
            adminReturn(2, '注册失败');
        }
    }

    /**
     * 用户下单
     * */
    public function simulationUserPay()
    {
        $user_list = $this->getUserList();
        $this->assign('user_list', $user_list);
        $this->assign('user_list_json', json_encode($user_list, JSON_UNESCAPED_UNICODE));

        $list = Db::name('order')->order('id desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '用户下单');
        return $this->view->fetch();
    }

    /**
     * 模拟用户下单
     * */
    public function userPay()
    {
        $input = Request()->param();

        $pay_price = $input['pay_price'] ? : rand(50, 300);
        $pay_time = $input['pay_time'] ? : date('Y-m-d');
        $up_user_id_arr = $input['up_user_id'];

        if (empty($up_user_id_arr)) adminReturn(2, '请选择下单用户');

        $up_user_id_arr = $this->delArrZero($up_user_id_arr);

        $user_id = $up_user_id_arr[count($up_user_id_arr) - 1] ? : 0;
        $up_user_id = $up_user_id_arr[count($up_user_id_arr) - 2] ? : 0;

        if ($up_user_id) {
            // 查询上级用户的会员等级


        }


        $data = [
            'user_id' => $user_id,
            'up_user_id' => $up_user_id,
            'pay_price' => $pay_price,
            'pay_time' => strtotime($pay_time)
        ];

        $res = Db::name('order')->insert($data);
        if ($res) {
            adminReturn(1, '下单成功');
        } else {
            adminReturn(2, '下单失败');
        }
    }

    /**
     * 执行时刻：【确认收货】
     * 1：获取用户会员等级升级规则及检测；
     * 2：直推奖励、级差奖励、服务津贴记录解冻；
     * */
    public function getUserUpRule($order_id)
    {
        Db::startTrans();
        try {
            $time = time();

            // 订单信息
            $order_info = Db::name('order')->where(['id' => $order_id])->find();
            // 下单用户id
            $user_id = $order_info['user_id'];
            // 上级用户id
            $up_user_id = $order_info['up_user_id'];

            if ($user_id) {
                /******************** 当前用户会员等级晋升处理 START ********************/

                // 查询当前用户的会员等级
                $own_level = Db::name('user')->where(['id' => $user_id])->value('level');
                if ($own_level == 2) {
                    //因为所有会员等级晋升规则中，只有【社区服务站】晋升【县区服务站】的情况下，才有一个条件（自行消费累计达 {$community_own_consume}）和自身挂钩，所以只需要判断该分支即可

                    /**
                     * 晋升社区服务站条件：
                     * 条件一：
                     * $own_community_vip_count：下级用户中需有 {$own_community_vip_count} 个VIP及以上等级
                     * $own_community_vip_consume：{$own_community_vip_count} 个VIP中均消费累计 {$own_community_vip_consume} 元
                     * 条件二：
                     * $own_community_own_consume：自行消费累计达 {$own_community_own_consume}
                     * */
                    $own_community_vip_count = Db::name('user_up_rule')->where(['name' => 'community_vip_count'])->value('value');
                    $own_community_vip_consume = Db::name('user_up_rule')->where(['name' => 'community_vip_consume'])->value('value');
                    $own_community_own_consume = Db::name('user_up_rule')->where(['name' => 'community_own_consume'])->value('value');

                    // 社区资格（下级用户中有$own_community_vip_count个VIP并且均累计消费$own_community_vip_consume）
                    $where['user_id'] = $user_id;
                    $where['level'] = ['egt', 2];
                    $where['all_consume'] = ['egt', $own_community_vip_consume];
                    // 满足条件一数量
                    $own_community_qualifications_count = Db::name('user')->where($where)->count();
                    if ($own_community_qualifications_count >= $own_community_vip_count) {
                        // 满足条件二数量
                        $own_all_consume = Db::name('user')->where(['id' => $user_id])->value('all_consume');

                        if ($own_all_consume >= $own_community_own_consume) {
                            // 用户等级晋升社区服务站
                            $own_level_data = [
                                'level' => 3,
                                'update_time' => $time
                            ];
                            Db::name('user')->where(['id' => $user_id])->update($own_level_data);
                        }
                    }
                }

                /******************** 当前用户会员等级晋升处理 END ********************/

                // 查询上级用户
                if ($up_user_id) {
                    // 首单直推比例

                    /******************** 上级用户会员等级晋升规则处理 START ********************/

                    // 查询上级用户的会员等级
                    $up_level = Db::name('user')->where(['id' => $up_user_id])->value('level');
                    switch ($up_level) {
                        case 2:
                            // VIP

                            /**
                             * 晋升社区服务站条件：
                             * 条件一：
                             * $community_vip_count：下级用户中需有 {$community_vip_count} 个VIP及以上等级
                             * $community_vip_consume：{$community_vip_count} 个VIP中均消费累计 {$community_vip_consume} 元
                             * 条件二：
                             * $community_own_consume：自行消费累计达 {$community_own_consume}
                             * */
                            $community_vip_count = Db::name('user_up_rule')->where(['name' => 'community_vip_count'])->value('value');
                            $community_vip_consume = Db::name('user_up_rule')->where(['name' => 'community_vip_consume'])->value('value');
                            $community_own_consume = Db::name('user_up_rule')->where(['name' => 'community_own_consume'])->value('value');

                            // 社区资格（下级用户中有$community_vip_count个VIP并且均累计消费$community_vip_consume）
                            $where['up_user_id'] = $up_user_id;
                            $where['level'] = ['egt', 2];
                            $where['all_consume'] = ['egt', $community_vip_consume];
                            // 满足条件一数量
                            $community_qualifications_count = Db::name('user')->where($where)->count();
                            if ($community_qualifications_count >= $community_vip_count) {
                                // 满足条件二数量
                                $own_all_consume = Db::name('user')->where(['id' => $up_user_id])->value('all_consume');

                                if ($own_all_consume >= $community_own_consume) {
                                    // 用户等级晋升社区服务站
                                    $level_data = [
                                        'level' => 3,
                                        'update_time' => $time
                                    ];
                                    Db::name('user')->where(['id' => $up_user_id])->update($level_data);
                                }
                            }
                            break;
                        case 3:
                            // 社区服务站

                            /**
                             * 晋升县区服务站条件：
                             * 条件一：自己是社区服务站
                             * 条件二：培育 {$county_diff_community_count} 个不同线社区服务站
                             * 条件三：总累计业绩达到 {$county_all_consume} 元
                             * */
                            $county_diff_community_count = Db::name('user_up_rule')->where(['name' => 'county_diff_community_count'])->value('value');
                            $county_all_consume = Db::name('user_up_rule')->where(['name' => 'county_all_consume'])->value('value');

                            if ($this->getAllConsume($up_user_id) >= $county_all_consume) {
                                //满足条件三

                                if ($this->diffCircuitCondition($up_user_id, 3, $county_diff_community_count)) {
                                    //满足条件二

                                    // 用户等级晋升县区服务站
                                    $level_data = [
                                        'level' => 4,
                                        'update_time' => $time
                                    ];
                                    Db::name('user')->where(['id' => $up_user_id])->update($level_data);
                                }
                            }
                            break;
                        case 4:
                            // 县区服务站

                            /**
                             * 晋升城市服务站条件：
                             * 条件一：自己是县区服务站
                             * 条件二：培育 {$city_diff_county_count} 个不同线县区服务站
                             * 条件三：总累计业绩达到 {$city_all_consume} 元
                             * */
                            $city_diff_county_count = Db::name('user_up_rule')->where(['name' => 'city_diff_county_count'])->value('value');
                            $city_all_consume = Db::name('user_up_rule')->where(['name' => 'city_all_consume'])->value('value');

                            if ($this->allConsume($up_user_id) >= $city_all_consume) {
                                //满足条件三

                                if ($this->diffCircuitCondition($up_user_id, 4, $city_diff_county_count)) {
                                    //满足条件二

                                    // 用户等级晋升城市服务站
                                    $level_data = [
                                        'level' => 5,
                                        'update_time' => $time
                                    ];
                                    Db::name('user')->where(['id' => $up_user_id])->update($level_data);
                                }
                            }
                            break;
                        case 5:
                            // 城市服务站

                            break;
                    }

                    /******************** 上级用户会员等级晋升规则处理 END ********************/
                }

                /******************** 收益解冻 START ********************/
                $data = [
                    'status' => 2,
                    'update_time' => $time
                ];
                Db::name('profit')->where(['order_id' => $order_id])->update($data);
                /******************** 收益解冻 END ********************/

                Db::commit();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /******************************* 计算某用户的累计业绩 START *******************************/
    // 查询出的用户id集合
    public $search_user_ids = [];

    /**
     * 获取某一个用户的所有下级用户id集合
     * @param int/array $in_user_id 用户id
     * @return array
     * */
    public function getSonUserIds($in_user_id)
    {
        if (is_array($in_user_id)) {
            $where['up_user_id'] = ['IN', $in_user_id];
        } else {
            $where['up_user_id'] = $in_user_id;
        }
        $user_id_list = Db::name('user')->field('id')->where($where)->select();

        $user_id_arr = array_column($user_id_list, 'id');
        if ($user_id_arr) {
            $this->search_user_ids = array_merge($this->search_user_ids, $user_id_arr);
            return $this->getSonUserIds($user_id_arr);
        } else {
            return $this->search_user_ids;
        }
    }

    // 调用示例
    public function getUser()
    {
        echo "<pre>";
        print_r($this->getSonUserIds(4));
        $this->search_user_ids = [];
        exit;
    }

    /**
     * 总累计业绩
     * @param int $user_id 用户id
     * @return float
     * */
    public function allConsume($user_id)
    {
        $son_user_ids = $this->getSonUserIds($user_id);
        if ($son_user_ids) {
            $all_consume = Db::name('order')->where(['user_id' => ['IN', $son_user_ids]])->sum('pay_price');
        } else {
            $all_consume = 0;
        }

        return sprintf('%.2f', $all_consume);
    }

    // 调用示例
    public function getAllConsume()
    {
        echo $this->allConsume(6);
    }
    /******************************* 计算某用户的累计业绩 END *******************************/


    /******************************* 查询某一个用户的培育不同线数量是否满足晋升条件 START *******************************/
    // 某用户的直接下级原始数据（集合）
    public $original_user_arr = [];
    // 某用户的直接下级原始数据下标
    public $key = 0;
    // 查询到满足条件的线路数量
    public $search_count = 0;
    // 标识是否已经循环过
    public $is_loop = false;

    /**
     * 会员等级：获取某个用户满足条件的培育路线
     * @param int $user_id    用户id
     * @param int $level      需要达到的等级
     * @param int $need_count 线路数量，当等于该数值用停止
     * @return bool
     * */
    public function diffCircuitCondition($user_id, $level, $need_count)
    {
        // 查询下级用户中是否有满足条件的用户
        $son_user_ids = Db::name('user')->field('id')->where(['up_user_id' => $user_id])->select();

        if ($this->is_loop === false) {
            $this->original_user_arr = $son_user_ids;
        } else {
            $son_user_ids = $son_user_ids ? : $this->original_user_arr[$this->key];
        }

        if ($son_user_ids && $need_count) {
            for ($i = 0; $i < count($son_user_ids); $i++) {
                $this->is_loop = true;

                $son_user_id = $son_user_ids[$i]['id'];
                file_put_contents(RUNTIME_PATH . 'circuit.txt', $son_user_id . '：循环ID' . PHP_EOL, FILE_APPEND);
                if ($son_user_id) {
                    $is_satisfy = Db::name('user')->where(['id' => $son_user_id, 'level' => ['egt', $level]])->count();
                    if ($is_satisfy) {
                        // 满足条件
                        file_put_contents(RUNTIME_PATH . 'circuit.txt', $son_user_id . '：满足条件' . PHP_EOL, FILE_APPEND);
                        // 累计满足条件的线路数量
                        ++$this->search_count;
                        if ($this->search_count >= $need_count) {
                            // 当累计线路数量满足晋升条件，停止循环，初始化初始变量 并 返回true
                            $this->original_user_arr = [];
                            $this->key = 0;
                            $this->search_count = 0;
                            $this->is_loop = false;

                            return true;
                        } else {
                            // 累计线路数量不满足晋升条件，切换下一个直接下级进行循环，继续递归查询
                            ++$this->key;
                            return $this->diffCircuitCondition($this->original_user_arr[$this->key]['id'], $level, $need_count);
                        }
                    } else {
                        // 不满足条件，继续递归查询
                        file_put_contents(RUNTIME_PATH . 'circuit.txt', $son_user_id . '：-------' . PHP_EOL, FILE_APPEND);
                        return $this->diffCircuitCondition($son_user_id, $level, $need_count);
                    }
                }
            }
        } else {
            return false;
        }
    }

    /**
     * 档数：获取某个用户满足条件的培育路线
     * @param int    $user_id    用户id
     * @param string $gear       需要达到的档数
     * @param int    $need_count 线路数量，当等于该数值用停止
     * @return int
     * */
    // 某用户的直接下级原始数据（集合）
    public $gear_original_user_arr = [];
    // 某用户的直接下级原始数据下标
    public $gear_key = 0;
    // 查询到满足条件的线路数量
    public $gear_search_count = 0;
    // 标识是否已经循环过
    public $gear_is_loop = false;
    // 用户档数
    public $gear_user = '';

    public function diffGearCircuitCondition($user_id, $gear, $need_count)
    {
        // 查询下级用户中是否有满足条件的用户
        $son_user_ids = Db::name('user')->field('id')->where(['up_user_id' => $user_id])->select();

        if ($this->gear_is_loop === false) {
            $this->gear_original_user_arr = $son_user_ids;
        } else {
            $son_user_ids = $son_user_ids ? : $this->gear_original_user_arr[$this->gear_key];
        }

        if ($son_user_ids && $need_count) {
            for ($i = 0; $i < count($son_user_ids); $i++) {
                $this->gear_is_loop = true;

                $son_user_id = $son_user_ids[$i]['id'];
                file_put_contents(RUNTIME_PATH . 'gear_circuit.txt', $son_user_id . '：循环ID，查询其档数是否为' . $gear . PHP_EOL, FILE_APPEND);
                if ($son_user_id) {
                    $is_satisfy = Db::name('user')->where(['id' => $son_user_id, 'gear' => $gear])->count();
                    if ($is_satisfy) {
                        // 满足条件
                        file_put_contents(RUNTIME_PATH . 'gear_circuit.txt', $son_user_id . '：满足条件' . PHP_EOL, FILE_APPEND);
                        // 累计满足条件的线路数量
                        ++$this->gear_search_count;
                        if ($this->gear_search_count >= $need_count) {
                            if ($gear == 'first_gear') {
                                $gear_user = 'second_gear';
                            } elseif ($gear == 'second_gear') {
                                $gear_user = 'third_gear';
                            }

                            // 当累计线路数量满足晋升条件，停止循环，初始化初始变量 并 返回true
                            $this->gear_original_user_arr = [];
                            $this->gear_key = 0;
                            $this->gear_search_count = 0;
                            $this->gear_is_loop = false;
                            $this->gear_user = '';

                            return $gear_user;
                        } else {
                            // 累计线路数量不满足晋升条件，切换下一个直接下级进行循环，继续递归查询
                            ++$this->gear_key;
                            return $this->diffGearCircuitCondition($this->gear_original_user_arr[$this->gear_key]['id'], $gear, $need_count);
                        }
                    } else {
                        // 不满足条件，继续递归查询
                        file_put_contents(RUNTIME_PATH . 'gear_circuit.txt', $son_user_id . '：-------' . PHP_EOL, FILE_APPEND);
                        return $this->diffGearCircuitCondition($son_user_id, $gear, $need_count);
                    }
                } else {
                    $list = Db::name('user')->field('id')->where(['up_user_id' => 83])->select();
                    echo "<pre>";
                    print_r($list);
                    exit;
                    echo "<pre>";
                    print_r($this->gear_original_user_arr);
                    exit;
                }
            }
        } else {
            return $this->gear_user;
        }
    }

    public function test3()
    {
        global $_GPC, $_W;

        $id = $_GPC['id'];
        $data = [];
        $keys = [$id];
        $this->getSonUser(4, $data, $keys);

        echo "<pre>";
        print_r($keys);
        echo "<br />";
    }


    public function getSonUser($id, &$data, &$keys)
    {
        $user_list = Db::name('user')->field('id')->where(['up_user_id' => $id])->select();
        if ($user_list) {
            foreach ($user_list as $k => $v) {
                $tmp_keys = $k;
                $tmp_keys[] = $v['id'];
                return $this->getSonUser($v['id'], $data, $tmp_keys);
            }
        } else {
            echo "<pre>";
            print_r($keys);
            echo "<br />";
        }
    }

    public $loop_arr = false;
    public $arr = [];

    public function test2($next_arr = [])
    {
        if (!$this->loop_arr) $next_arr = $this->getUserList(82);

        if ($this->arr) {
            $for_arr = $this->arr;
            foreach ($this->arr as $k => $v) {
                $for_arr[] = array_column($v, 'id');
                return $this->test2($next_arr);
            }
        } else {
            /*if ($next_arr) {
                foreach ($next_arr as $k => $v) {
                    if ($v['id']) {
                        file_put_contents(RUNTIME_PATH . 'test.txt', $v['id'] . PHP_EOL, FILE_APPEND);
                        $this->arr[$k][] = $v['id'];
//                    return $this->test2($v['son_user_list']);
                    } else {
                        echo "<pre>";
                        print_r($this->arr);
                        exit;
                    }
                }
            }*/
            $this->arr = array_column($next_arr, 'id');
            return $this->test2($next_arr);
        }
    }

    public function test()
    {

        $A = ['红色', '黄色'];
        $B = ['M', 'L', 'XL'];
        $D = ['1', '2', '3', '4'];

// 先将各属性值处理成一个整体
        $list[] = $A;
        $list[] = $B;
        $list[] = $D;

        $res = array();
        foreach ($list as $k => $v) {
            $res = $this->getCombinationToString($v);
        }
        echo "<pre>";
        print_r($res);
        exit;

    }


    /**
     * 获取组合的结果
     * [@author](https://my.oschina.net/arthor) 18y
     * @anotherdate 2019-04-27T09:49:44+0800
     * [@param](https://my.oschina.net/u/2303379)       array                         $val 组合内容
     * [@return](https://my.oschina.net/u/556800)      [type]                        [description]
     */
    function getCombinationToString($val)
    {
        // 保存上一个的值
        static $res = array();
        if (empty($res)) {
            $res = $val;
        } else {
            // 临时数组保存结合的结果
            $list = array();
            foreach ($res as $k => $v) {
                foreach ($val as $key => $value) {
                    $list[] = $v . '_' . $value;
                }
            }
            $res = $list;
        }
        return $res;
    }

    /**
     * 检测用户档数（一档，二挡，三挡）
     * @param int $user_id 用户id
     * @return string
     * */
    public function checkUserGear($user_id)
    {
        $first_gear_diff_city_circuit = Db::name('retire_fund_rule')->where(['name' => 'first_gear_diff_city_circuit'])->value('value');
        $second_gear_diff_first_circuit = Db::name('retire_fund_rule')->where(['name' => 'second_gear_diff_first_circuit'])->value('value');
        $third_gear_diff_second_circuit = Db::name('retire_fund_rule')->where(['name' => 'third_gear_diff_second_circuit'])->value('value');

        /**
         * 检测用户是否满足一档条件：培育两条不同线路的城市服务站
         * */
        $first_gear_res = $this->diffCircuitCondition($user_id, 5, $first_gear_diff_city_circuit);
        if ($first_gear_res) {
            $this->gear_user = 'first_gear';
            /**
             * 检测用户是否满足二档条件：培育两条不同线路的城市服务站
             * */
            $second_gear_res = $this->diffGearCircuitCondition($user_id, 'first_gear', $second_gear_diff_first_circuit);
            if ($second_gear_res == 'second_gear') {
                $this->gear_user = 'second_gear';
                /**
                 * 检测用户是否满足三档条件：培育两条不同线路的城市服务站
                 * */
                $third_gear_res = $this->diffGearCircuitCondition($user_id, 'second_gear', $third_gear_diff_second_circuit);
                if ($third_gear_res == 'third_gear') {
                    $this->gear_user = 'third_gear';
                }
            }
        }

        return $this->gear_user;
    }

    /**
     * 测试 服务商档数
     * */
    public function testGear()
    {
        echo $this->diffGearCircuitCondition(82, 'second_gear', 1);
        exit;
//
//        file_put_contents(RUNTIME_PATH . 'gear_circuit.txt', '');

        echo "<pre>";
        echo '服务商档数为：' . $this->checkUserGear(82);

        $this->gear_original_user_arr = [];
        $this->gear_key = 0;
        $this->gear_search_count = 0;
        $this->gear_is_loop = false;
        $this->gear_user = '';

//        echo "<pre>";
//        print_r(file_get_contents(RUNTIME_PATH . 'gear_circuit.txt'));
    }


    /**
     * 测试 调用示例
     * */
    public function testUser()
    {
        file_put_contents(RUNTIME_PATH . 'circuit.txt', '');

        echo "<pre>";
        echo $this->diffCircuitCondition(4, 3, 2) ? '成功' : '失败';
        $this->original_user_arr = [];
        $this->key = 0;
        $this->search_count = 0;
        $this->is_loop = false;

        echo "<pre>";
        print_r(file_get_contents(RUNTIME_PATH . 'circuit.txt'));
    }

    /******************************* 查询某一个用户的培育不同线数量是否满足晋升条件 END *******************************/

    /**
     * 调用测试
     * */
    public function testFunctions()
    {
        $this->assign('title', '调用测试');
        return $this->view->fetch();
    }

}
